<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  

  
  <title>shiro并发登录控制 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="并发登录人数控制在某些项目中可能会遇到如没买个账户同事有一个人登录或几个人同时登陆了，如果同时又多人登录；要么不让后者登录；要么踢出前者(强制退出).比如 spring secrity就直接提供了相应的功能；Shiro的话没有提供默认的实现，不过可以很容易的在Shiro中加入这个功能.">
<meta name="keywords" content="shiro">
<meta property="og:type" content="article">
<meta property="og:title" content="shiro并发登录控制">
<meta property="og:url" content="http://yoursite.com/2018/10/12/2018-03-19-shiro并发控制/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="并发登录人数控制在某些项目中可能会遇到如没买个账户同事有一个人登录或几个人同时登陆了，如果同时又多人登录；要么不让后者登录；要么踢出前者(强制退出).比如 spring secrity就直接提供了相应的功能；Shiro的话没有提供默认的实现，不过可以很容易的在Shiro中加入这个功能.">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://img.w3cschool.cn/attachments/image/wk/shiro/28.png">
<meta property="og:updated_time" content="2018-11-01T14:24:04.943Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shiro并发登录控制">
<meta name="twitter:description" content="并发登录人数控制在某些项目中可能会遇到如没买个账户同事有一个人登录或几个人同时登陆了，如果同时又多人登录；要么不让后者登录；要么踢出前者(强制退出).比如 spring secrity就直接提供了相应的功能；Shiro的话没有提供默认的实现，不过可以很容易的在Shiro中加入这个功能.">
<meta name="twitter:image" content="https://img.w3cschool.cn/attachments/image/wk/shiro/28.png">
  
    <link rel="alternate" href="/org/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/org/css/style.css">
</head>
</html>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/org/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/org/">Home</a>
        
          <a class="main-nav-link" href="/org/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/org/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2018-03-19-shiro并发控制" class="article article-type-post" itemscope="" itemprop="blogPost">
  <div class="article-meta">
    <a href="/org/2018/10/12/2018-03-19-shiro并发控制/" class="article-date">
  <time datetime="2018-10-12T09:03:30.000Z" itemprop="datePublished">2018-10-12</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      shiro并发登录控制
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h3 id="并发登录人数控制"><a href="#并发登录人数控制" class="headerlink" title="并发登录人数控制"></a>并发登录人数控制</h3><p>在某些项目中可能会遇到如没买个账户同事有一个人登录或几个人同时登陆了，如果同时又多人登录；要么不让后者登录；要么踢出前者(强制退出).比如 spring secrity就直接提供了相应的功能；Shiro的话没有提供默认的实现，不过可以很容易的在Shiro中加入这个功能.</p>
<a id="more"></a>
<p>示例代码基于《第十六章 综合实例》完成，通过 Shiro Filter 机制扩展 KickoutSessionControlFilter 完成。</p>
<p><strong>首先来看看如何配置使用（spring-config-shiro.xml）</strong></p>
<p>kickoutSessionControlFilter 用于控制并发登录人数的</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;kickoutSessionControlFilter&quot; </span><br><span class="line">class=&quot;com.github.zhangkaitao.shiro.chapter18.web.shiro.filter.KickoutSessionControlFilter&quot;&gt;</span><br><span class="line">    &lt;property name=&quot;cacheManager&quot; ref=&quot;cacheManager&quot;/&gt;</span><br><span class="line">    &lt;property name=&quot;sessionManager&quot; ref=&quot;sessionManager&quot;/&gt;</span><br><span class="line">    &lt;property name=&quot;kickoutAfter&quot; value=&quot;false&quot;/&gt;</span><br><span class="line">    &lt;property name=&quot;maxSession&quot; value=&quot;2&quot;/&gt;</span><br><span class="line">    &lt;property name=&quot;kickoutUrl&quot; value=&quot;/login?kickout=1&quot;/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<ul>
<li>cacheManager：使用 cacheManager 获取相应的 cache 来缓存用户登录的会话；用于保存用户—会话之间的关系的；</li>
<li>sessionManager：用于根据会话 ID，获取会话进行踢出操作的；</li>
<li>kickoutAfter：是否踢出后来登录的，默认是 false；即后者登录的用户踢出前者登录的用户；</li>
<li>maxSession：同一个用户最大的会话数，默认 1；比如 2 的意思是同一个用户允许最多同时两个人登录；</li>
<li>kickoutUrl：被踢出后重定向到的地址；</li>
</ul>
<p>shiroFilter 配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;shiroFilter&quot; class=&quot;org.apache.shiro.spring.web.ShiroFilterFactoryBean&quot;&gt;</span><br><span class="line">     &lt;property name=&quot;securityManager&quot; ref=&quot;securityManager&quot;/&gt;</span><br><span class="line">     &lt;property name=&quot;loginUrl&quot; value=&quot;/login&quot;/&gt;</span><br><span class="line">     &lt;property name=&quot;filters&quot;&gt;</span><br><span class="line">         &lt;util:map&gt;</span><br><span class="line">             &lt;entry key=&quot;authc&quot; value-ref=&quot;formAuthenticationFilter&quot;/&gt;</span><br><span class="line">             &lt;entry key=&quot;sysUser&quot; value-ref=&quot;sysUserFilter&quot;/&gt;</span><br><span class="line">             &lt;entry key=&quot;kickout&quot; value-ref=&quot;kickoutSessionControlFilter&quot;/&gt;</span><br><span class="line">         &lt;/util:map&gt;</span><br><span class="line">     &lt;/property&gt;</span><br><span class="line">     &lt;property name=&quot;filterChainDefinitions&quot;&gt;</span><br><span class="line">         &lt;value&gt;</span><br><span class="line">             /login = authc</span><br><span class="line">             /logout = logout</span><br><span class="line">             /authenticated = authc</span><br><span class="line">             /** = kickout,user,sysUser</span><br><span class="line">         &lt;/value&gt;</span><br><span class="line">     &lt;/property&gt;</span><br><span class="line"> &lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<p>此处配置除了登录等之外的地址都走 kickout 拦截器进行并发登录控制。</p>
<p><strong>测试</strong></p>
<p>此处因为 maxSession=2，所以需要打开 3 个浏览器（需要不同的浏览器，如 IE、Chrome、Firefox），分别访问 <code>http://localhost:8080/chapter18/</code> 进行登录；然后刷新第一次打开的浏览器，将会被强制退出，如显示下图：</p>
<p><img src="https://img.w3cschool.cn/attachments/image/wk/shiro/28.png" alt="img"></p>
<p>KickoutSessionControlFilter 核心代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception &#123;</span><br><span class="line">    Subject subject = getSubject(request, response);</span><br><span class="line">    if(!subject.isAuthenticated() &amp;&amp; !subject.isRemembered()) &#123;</span><br><span class="line">        //如果没有登录，直接进行之后的流程</span><br><span class="line">        return true;</span><br><span class="line">    &#125;</span><br><span class="line">    Session session = subject.getSession();</span><br><span class="line">    String username = (String) subject.getPrincipal();</span><br><span class="line">    Serializable sessionId = session.getId();</span><br><span class="line">    //TODO 同步控制</span><br><span class="line">    Deque&lt;Serializable&gt; deque = cache.get(username);</span><br><span class="line">    if(deque == null) &#123;</span><br><span class="line">        deque = new LinkedList&lt;Serializable&gt;();</span><br><span class="line">        cache.put(username, deque);</span><br><span class="line">    &#125;</span><br><span class="line">    //如果队列里没有此sessionId，且用户没有被踢出；放入队列</span><br><span class="line">    if(!deque.contains(sessionId) &amp;&amp; session.getAttribute(&quot;kickout&quot;) == null) &#123;</span><br><span class="line">        deque.push(sessionId);</span><br><span class="line">    &#125;</span><br><span class="line">    //如果队列里的sessionId数超出最大会话数，开始踢人</span><br><span class="line">    while(deque.size() &gt; maxSession) &#123;</span><br><span class="line">        Serializable kickoutSessionId = null;</span><br><span class="line">        if(kickoutAfter) &#123; //如果踢出后者</span><br><span class="line">            kickoutSessionId = deque.removeFirst();</span><br><span class="line">        &#125; else &#123; //否则踢出前者</span><br><span class="line">            kickoutSessionId = deque.removeLast();</span><br><span class="line">        &#125;</span><br><span class="line">        try &#123;</span><br><span class="line">            Session kickoutSession =</span><br><span class="line">                sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));</span><br><span class="line">            if(kickoutSession != null) &#123;</span><br><span class="line">                //设置会话的kickout属性表示踢出了</span><br><span class="line">                kickoutSession.setAttribute(&quot;kickout&quot;, true);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Exception e) &#123;//ignore exception</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    //如果被踢出了，直接退出，重定向到踢出后的地址</span><br><span class="line">    if (session.getAttribute(&quot;kickout&quot;) != null) &#123;</span><br><span class="line">        //会话被踢出了</span><br><span class="line">        try &#123;</span><br><span class="line">            subject.logout();</span><br><span class="line">        &#125; catch (Exception e) &#123; //ignore</span><br><span class="line">        &#125;</span><br><span class="line">        saveRequest(request);</span><br><span class="line">        WebUtils.issueRedirect(request, response, kickoutUrl);</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line">    return true;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此处使用了 Cache 缓存用户名—会话 id 之间的关系；如果量比较大可以考虑如持久化到数据库 / 其他带持久化的 Cache 中；另外此处没有并发控制的同步实现，可以考虑根据用户名获取锁来控制，减少锁的粒度。</p>
<p>另外可参考 JavaEE 项目开发脚手架，其提供了后台踢出用户的功能：<br><a href="https://github.com/zhangkaitao/es/blob/master/web/src/main/java/com/sishuok/es/sys/user/web/controller/UserOnlineController.java" target="_blank" rel="noopener">https://github.com/zhangkaitao/es/blob/master/web/src/main/java/com/sishuok/es/sys/user/web/controller/UserOnlineController.java</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2018/10/12/2018-03-19-shiro并发控制/" data-id="cjoztxu3i00181wije7lj070e" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/org/tags/shiro/">shiro</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/org/2018/10/12/2018-03-19-shiro综合实例/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          shiro综合实例
        
      </div>
    </a>
  
  
    <a href="/org/2018/10/12/2018-05-03-SVN文档目录规范/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">SVN文档规划</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/SVN/">SVN</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/Spring-secrity/">Spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hexo/">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hibenrate/">hibenrate</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jekyll/">jekyll</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jenkins/">jenkins</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/redis/">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/shiro/">shiro</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spingMVC/">spingMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring-cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-secrity/">spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springMVC/">springMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springboot/">springboot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/生活/">生活</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/org/tags/SVN/" style="font-size: 12px;">SVN</a> <a href="/org/tags/Spring-secrity/" style="font-size: 10px;">Spring-secrity</a> <a href="/org/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/org/tags/hibenrate/" style="font-size: 10px;">hibenrate</a> <a href="/org/tags/jekyll/" style="font-size: 10px;">jekyll</a> <a href="/org/tags/jenkins/" style="font-size: 10px;">jenkins</a> <a href="/org/tags/redis/" style="font-size: 16px;">redis</a> <a href="/org/tags/shiro/" style="font-size: 18px;">shiro</a> <a href="/org/tags/spingMVC/" style="font-size: 10px;">spingMVC</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring cloud</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring-cloud</a> <a href="/org/tags/spring-secrity/" style="font-size: 12px;">spring-secrity</a> <a href="/org/tags/springMVC/" style="font-size: 14px;">springMVC</a> <a href="/org/tags/springboot/" style="font-size: 20px;">springboot</a> <a href="/org/tags/生活/" style="font-size: 10px;">生活</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/11/">November 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/10/">October 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/org/2018/11/27/redis07-zookeeper-kafka集群部署以及如何使用简单介绍/">redis07-zookeeper+kafka集群部署以及如何使用简单介绍</a>
          </li>
        
          <li>
            <a href="/org/2018/11/13/redis06-cluster实现高可用性/">redis06-cluster实现高可用性</a>
          </li>
        
          <li>
            <a href="/org/2018/11/12/redis05-在项目中搭建读写分-高可用-多master的redis-cluster集群/">redis05-在项目中搭建读写分+高可用+多master的redis cluster集群</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/在项目中用经典的三节点方式部署哨兵集群-笔记/">在项目中用经典的三节点方式部署哨兵集群-笔记</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/redis哨兵的多个核心底层原理-笔记/">redis哨兵的多个核心底层原理-笔记</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/org/" class="mobile-nav-link">Home</a>
  
    <a href="/org/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>


  <link rel="stylesheet" href="/org/fancybox/jquery.fancybox.css">
  <script src="/org/fancybox/jquery.fancybox.pack.js"></script>


<script src="/org/js/script.js"></script>



  </div>
</body>
</html>